// ping ftp.gnu.org     可以获取该FTP服务器的IP地址
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

#define PORT 5566

int main(void)
{
    int sockfd, newsockfd;
    struct sockaddr_in addr; //定义IPv4套接口地址数据结构addr
    int addr_len = sizeof(struct sockaddr_in);
    char msgbuf[256]; //发送和接收数据缓冲区
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket created error!\n");
        exit(1);
    }
    else
    {
        printf("socket created successfully!\n");
        printf("socket id: %d\n", sockfd);
    }
    bzero(&addr, sizeof(struct sockaddr_in)); //清空表示地址的结构体变量
    addr.sin_family = AF_INET;                //设置addr的成员变量
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY); // IP地址设置为本机IP
    if (bind(sockfd, (struct sockaddr *)(&addr), sizeof(struct sockaddr)) < 0)
    {
        perror("bind error!\n");
        exit(1);
    }
    else
    {
        printf("bind port successfully!\n");
        printf("local port:%d\n", PORT);
    }
    if (listen(sockfd, 5) < 0) //调用listen函数监听端口号，能同时处理的最大连接请求书为5
    {
        perror("listen error!\n");
        exit(1);
    }
    else
    {
        printf("listening......\n"); //监听中
    }
    if ((newsockfd = accept(sockfd, (struct sockaddr *)(&addr), &addr_len)) < 0)
    {
        perror("accept error!\n");
    }
    else
    {
        printf("connect from %s\n", inet_ntoa(addr.sin_addr));
        if (read(newsockfd, msgbuf, sizeof(msgbuf)) <= 0) //调用read读取信息
        {
            perror("accept error!\n");
        }
        else
        {
            printf("message:\n%s \n", msgbuf); //输出接收到的信息
        }
    }
    return 0;
}